import {Component, EventEmitter, forwardRef, Input, Output} from '@angular/core';
import {ImagePickerObject} from "@common/ImagePickerObject";
import {NativePickerProvider} from "@providers/natives/native-picker";
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from "@angular/forms";
import {NativeUploadProvider} from "@providers/natives/native-upload";
import {NativeCameraProvider} from "@providers/natives/native-camera";
import {ActionSheetController} from "ionic-angular";
import {env} from "@env/environment";

/**
 * Generated class for the ImagePickerComponent component.
 *
 * See https://angular.io/api/core/Component for more info on Angular
 * Components.
 */
@Component({
  selector: 'image-picker',
  templateUrl: 'image-picker.html',
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => ImagePickerComponent),
    multi: true
  }],
})
export class ImagePickerComponent implements ControlValueAccessor {

  private propagateChange = (_: any) => {
  };

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
  }

  setDisabledState(isDisabled: boolean): void {
  }

  writeValue(value: any): void {
    this.imageList = value || [];
  }

  imageList: ImagePickerObject[] = [];

  @Output() imageChangList = new EventEmitter<ImagePickerObject[]>();
  @Input() canDel: boolean = true;
  @Input() canAdd: boolean = true;
  @Input() max = 0;
  @Input() upload: boolean = false;// 是否自动上传
  @Input() mode: string = 'camera';//模式选择：camera--照相  image--从图库选择  all--既可以拍照又可以从图库选择
  @Output() addEvent = new EventEmitter<ImagePickerObject[]>();
  @Output() delEvent = new EventEmitter<ImagePickerObject[]>();
  @Input() isFileServer: boolean = false;// 是否从文件服务器获取图片数据

  constructor(private nativePicker: NativePickerProvider,
              private nativeUpload: NativeUploadProvider,
              private nativeCamera: NativeCameraProvider,
              private actionSheetCtrl: ActionSheetController) {
  }

  canShowAdd(): boolean {
    return this.max == 0 ? this.canAdd : this.imageList.length < this.max;
  }

  addImage() {
    switch (this.mode) {
      case "camera":
        this.camera();
        break;
      case "image":
        this.choosePicker();
        break;
      default:
        this.useASComponent()
    }
  }

  camera() {
    this.nativeCamera.openCamera().then(file => {
      if (this.upload) {
        this.nativeUpload.upload(file.base64).then(fileData => {
          let file = new ImagePickerObject();
          file.url = fileData['FILE_URL'];
          this.add([file]);
        });
      } else {
        this.add([file]);
      }
    })
  }

  choosePicker() {
    let options = {max: this.max};
    this.nativePicker.choose(options).then(v => {
      if (this.max != 0) v.splice(this.max, v.length - this.max);
      if (this.upload) {
        let files: ImagePickerObject[] = [];
        for (let i = 0; i < v.length; i++) {
          this.nativeUpload.upload(v[i].base64).then(fileData => {
            Object.assign(v[i], fileData);
            let file = new ImagePickerObject();
            file.url = fileData['FILE_URL'];
            files.push(file);
            if (i == v.length - 1) this.add(files);
          });
        }
      } else {
        this.add(v);
      }
    })
  }

  // 使用ionic中的ActionSheet组件
  useASComponent() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择',
      buttons: [
        {
          text: '拍照',
          handler: () => {
            this.camera();
          }
        },
        {
          text: '从手机相册选择',
          handler: () => {
            this.choosePicker();
          }
        },
        {
          text: '取消',
          role: 'cancel',
        }
      ]
    });
    actionSheet.present();
  }

  delImage(image, i) {
    if (!this.canDel) {
      return;
    }
    let that = this;
    that.actionSheetCtrl.create({
      buttons: [
        {
          text: '删除',
          role: 'destructive',
          handler: () => {
            this.del([image]);
          }
        },
        {
          text: '取消',
          role: 'cancel'
        }
      ]
    }).present();
  }

  add(list: ImagePickerObject[]) {
    this.imageList = [...this.imageList, ...list];
    this.propagateChange(this.imageList);
    this.addEvent.emit(list);
  }

  del(list: ImagePickerObject[]) {
    for (let i = 0; i < list.length; i++) {
      let v = list[i];
      this.imageList.splice(this.imageList.indexOf(v), 1)
    }
    this.delEvent.emit(list);
  }

  getImageUrl(url) {
    if (this.isFileServer && url.indexOf("http") != -1)
      return env.app_serve_url + '/FormUpload/download.do?filename=a.jpg&url=' + url;
    return url
  }
}
